var request = require('request');
var util = require('util');
var layer = require('layer');
var json = require('{js}/polyfill/json');

return function(e, elem){
    e && e.stopPropagation();

    var that = this;
    var voucherForm = this.element.find('form');
    var formData = util.getData(voucherForm, '.table-row', 'voucherlines').result;
    if(voucherForm.find('.j-save').hasClass('ui-button-disabled')){
        return
    }

    //借贷不平
    if(that.data.total_debite !== that.data.total_credit){
        layer.message('error', '录入借贷不平')
        return
    }

    //数据没有填完整
    var errData = null;
    Nui.each(formData.voucherlines, function(v, i){
        if(!v.summary || !v.subject || (!v.debite && !v.credit)){
            errData = {};
            if(!v.summary){
                errData.name = 'summary';
                errData.message = '摘要不能为空';
            }
            else if(!v.subject){
                errData.name = 'subject';
                errData.message = '会计科目不能为空';
            }
            else{
                errData.name = 'debite';
                errData.message = '借方金额不能为空';
            }
            errData.index = i;

            if(i === 0 || v.debite || v.credit){
                return false;
            }
        }
        //删除脏数据
        if(!v.summary || !v.subject){
            delete formData.voucherlines[i]
        }
        errData = null;
    })
    if(errData){
        if(errData.index === 0){
            errData.message = '第一行' + errData.message
        }
        that.showEdit(null, voucherForm.find('.table-row:eq('+ errData.index +') .col-'+ errData.name + ' .cell-edit'));
        layer.message('error', errData.message);
        return
    }
    
    formData.vouchers = [];
    Nui.each(formData.voucherlines, function(v){
        if(v){
            formData.vouchers.push(v);
        }
    })
    delete formData.voucherlines

    var newFormData = $.extend(true, {}, formData);

    formData.vouchers = json.stringify(formData.vouchers);

    request.post('voucher.json', formData, {
        200:function(res){
            if(elem && elem.hasClass('j-saveadd')){
                that.initTemplate()
            }
            else{
                that.render(newFormData);
            }
        }
    }, '正在保存凭证...')
}